<?php
if(!isset($_GET['cmd'])) die('cmd');
$debug = isset($_GET['cmd']);

$db_hostspec = "localhost";
$db_database = "oguievet_babel";
$db_username = "oguievet_babel";
$db_password = "babel5";

mysql_connect($db_hostspec, $db_username, $db_password) or die('Problem 1'); 
mysql_select_db($db_database) or die('Problem 2');
mysql_query("SET NAMES 'utf8'");

switch($_GET['cmd']) {
case 'lookup-e2s':
	if(!isset($_GET['word'])) die('word');
	$word = clean_str($_GET['word']);
	
	$words = array();
	$sql = "SELECT spanish FROM dict WHERE english='$word';";
	$result = mysql_query($sql) or mysql_error();
	if($row = mysql_fetch_assoc($result)) {
		array_push($words, $row['spanish']);
	}
	print json_encode($words);
	break;
	
case 'lookup-s2e':
	if(!isset($_GET['word'])) die('word');
	$word = clean_str($_GET['word']);
	
	$words = array();
	$sql = "SELECT english FROM dict WHERE spanish='$word';";
	$result = mysql_query($sql) or mysql_error();
	if($row = mysql_fetch_assoc($result)) {
		array_push($words, $row['english']);
	}
	print json_encode($words);
	break;
	
case 'wordlist':
	if(!isset($_GET['user'])) die('user');
	$user = clean_str($_GET['user']);
	
	$words = array();
	$sql = "SELECT english, spanish FROM words WHERE user='$user' ORDER BY added DESC;";
	$result = mysql_query($sql) or mysql_error();
	while($row = mysql_fetch_assoc($result)) {
		$words[$row['english']] = $row['spanish'];
	}
	
	print json_encode($words);
	break;

case 'addword':
	if(!isset($_GET['user'])) die('user');
	if(!isset($_GET['eword'])) die('eword');
	if(!isset($_GET['sword'])) die('sword');
	$user = clean_str($_GET['user']);
	$eword = clean_str($_GET['eword']);
	$sword = clean_str($_GET['sword']);
	
	$sql = "INSERT INTO words (user, english, spanish) VALUES ('$user', '$eword', '$sword') ON DUPLICATE KEY UPDATE user=VALUES(user), english=VALUES(english), spanish=VALUES(spanish);";
	mysql_query($sql) or mysql_error();
	break;

case 'deleteword':
	if(!isset($_GET['user'])) die('user');
	if(!isset($_GET['eword'])) die('eword');
	if(!isset($_GET['sword'])) die('sword');
	$user = clean_str($_GET['user']);
	$eword = clean_str($_GET['eword']);
	$sword = clean_str($_GET['sword']);
	
	$sql = "DELETE FROM words WHERE user='$user' AND english='$eword' AND spanish='$sword' LIMIT 1;";
	mysql_query($sql) or mysql_error();
	if($debug) echo $sql . "\n";	
	break;	
	
case 'flashlist':
	if(!isset($_GET['user'])) die('user');
	$user = clean_str($_GET['user']);
	
	$cards = array(
		array("e"=>"cow", "s"=>"cowawa"),
		array("e"=>"tire", "s"=>"tiro")
	);
	
	print json_encode($cards);
	break;
}

function clean_str($str) {
	$bad = array("'", '"', '%', '$');
	return str_replace($bad, "", $str);
}
?>
